package 排序;


public class 二叉树排序 {

    //     由小到大
    private static void sort(int[] nums) {
        TwoTree twoTree = new TwoTree();
        for (int i = 0; i < nums.length; i++) {
            twoTree.insert(nums[i]);
        }
//        twoTree.insert(2);
//        twoTree.insert(3);
//        twoTree.insert(1);
//        System.out.println(twoTree.getData());
//        System.out.println(twoTree.getLeft().getData());
//        System.out.println(twoTree.getRight().getData());
        twoTree.leftTraverse(); // 从小到大
        twoTree.rightTraverse(); // 从大到小
    }

    public static void main(String[] args) {
        int[] ints = {3, 4, 51, 2, 5, 4576, 3, 4, 234, 7, 89};
        sort(ints);
    }
}

class TwoTree {
    private Integer data;
    private TwoTree left;
    private TwoTree right;

    public TwoTree() {
        this.data = null;
        this.left = null;
        this.right = null;
    }

    public Integer getData() {
        return data;
    }

    public TwoTree getLeft() {
        return left;
    }

    public TwoTree getRight() {
        return right;
    }

    public void setData(Integer data) {
        this.data = data;
    }

    public void setLeft(TwoTree left) {
        this.left = left;
    }

    public void setRight(TwoTree right) {
        this.right = right;
    }

    public void insert(int data) {
        if (getData() == null) {
            setData(data);
            System.out.println("insert----" + data);
            return;
        }
        if (data <= getData()) {
            if (getLeft() == null) {
                setLeft(new TwoTree());
            }
            getLeft().insert(data);
        } else {
            if (getRight() == null) {
                setRight(new TwoTree());
            }
            getRight().insert(data);
        }
    }

    public void leftTraverse() {
        if (getLeft() != null) {
            getLeft().leftTraverse();
        }
        System.out.println(getData());
        if (getRight() != null) {
            getRight().leftTraverse();
        }
    }

    public void rightTraverse() {
        if (getRight() != null) {
            getRight().rightTraverse();
        }
        System.out.println(getData());
        if (getLeft() != null) {
            getLeft().rightTraverse();
        }
    }
}
